// @algorithm @lc id=102 lang=cpp 
// @title binary-tree-level-order-traversal


// #define print(...)
// @test([3,9,20,null,null,15,7])=[[3],[9,20],[15,7]]
// @test([1])=[[1]]
// @test([])=[]
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        function<void(TreeNode*)> bfs = [&](TreeNode * node){
            if(!node) return;
            list<TreeNode*> q;
            q.push_back(node);
            while(int n = q.size()){
                res.emplace_back(vector<int>(n, 0));
                auto it = res.back().begin();
                while(n--){
                    auto t = q.front(); q.pop_front();
                    *it++ = t->val;
                    if(t->left) q.push_back(t->left);
                    if(t->right)q.push_back(t->right);
                }
            }
        };
        bfs(root);
        return res;
    }
};
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */